package com.axonactive.yolo.validation;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.axonactive.yolo.domain.UserEmail;
import com.axonactive.yolo.dto.ResetPasswordRequestParameters;
import com.axonactive.yolo.service.interfaces.UserEmailService;
import com.axonactive.yolo.util.Utils;

@Component
public class ResetPasswordRequestValidator implements Validator {
	@Autowired
	private UserEmailService userEmailService;

	@Override
	public boolean supports(Class<?> clazz) {
		return ResetPasswordRequestParameters.class.isAssignableFrom(clazz);
	}

	@Override
	public void validate(Object target, Errors errors) {
		ResetPasswordRequestParameters resetPasswordRequestParameters = (ResetPasswordRequestParameters) target;

		ValidationUtils.rejectIfEmpty(errors, "userEmail", "email.notnull");

		boolean nullUser = false;
		UserEmail userEmail = userEmailService
				.findByEmailString(resetPasswordRequestParameters
						.getUserEmail());
		if (userEmail == null) {
			nullUser = true;
		} else if (userEmail.getUser() == null) {
			nullUser = true;
		}

		if (!"".equals(resetPasswordRequestParameters.getUserEmail())
				&& !Utils.isValidEmail(resetPasswordRequestParameters
						.getUserEmail())) {
			errors.rejectValue("userEmail", "email.invalid");
		} else if (!"".equals(resetPasswordRequestParameters.getUserEmail())
				&& nullUser) {
			errors.rejectValue("userEmail", "email.not.exist");
		}
	}

}
